// pages/goods/detail/index.js
var app = getApp();
var core = app.requirejs('core');
var diypage = app.requirejs('biz/diypage'); //自定义商品详情模板 template
var diyad = app.requirejs('biz/ad');
// var diyform = app.requirejs('biz/diyform');
// var goodspicker = app.requirejs('biz/goodspicker');
var $ = app.requirejs('jquery');
// var parser = app.requirejs('wxParse/wxParse');
// const Crypto = require('../../../utils/aes.js')
// var hasOption = 0;
const util = require('../../../utils/util.js');
// var selectdate = app.requirejs('biz/selectdate');
const api = require("../../../utils/api.js")
const authScope = require("../../../utils/auth.js")
Page(app.sr.page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    circular: true, //轮播图
    detailsel: true, //规格
    total: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let isLogin = app.checkAuth();
    this.setData({
      isLogin
    })
    let _this = this
    // let pageview = util.getCurrentPageUrl()
    // app.setCache('currentUrl', 'pages/goods/detail/index?id=' + options.id)
    _this.initFunction(options)
    _this.getcartGoodsCount()
    _this.friendGiftStatus()
  },

  initFunction: function (options) {
    let $this = this
    var isIpx = app.getCache('isIpx');
    if (isIpx) {
      $this.setData({
        isIpx: true,
        iphonexnavbar: 'fui-iphonex-navbar'
      })
    } else {
      $this.setData({
        isIpx: false,
        iphonexnavbar: ''
      })
    }
    $this.setData({
      options: options
    });
    $this.getDetail(options);

    diypage.get(this, 'goodsdetail', {
      goodsId: options.id
    }, function (res) {
      var diypage = res.diypage.data;
      diypage = diypage ? JSON.parse(diypage) : []
      $.each(diypage, function (id, item) {
        if (item.components == 'mofang') {
          wx.getSystemInfo({
            success: function (res) {

              let ScreenWidth = res.screenWidth
              let ratio = ScreenWidth / 304
              item.options.combineLists.map((v, i) => {
                v.width = (v.width - 1) * ratio
                v.height = v.height * ratio
                v.top = v.top * ratio
                v.left = v.left * ratio
              })
            },
          })
        }
      })
      diypage = {
        currentTemplate: diypage
      }
      $this.setData({
        diypages: diypage
      })
    });


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let thumb = ''
    if (JSON.stringify(this.data.moreSel) != '{}') {
      thumb = this.data.moreSel.shareimg
    } else {
      thumb = this.data.goods.thumb
    }
    this.setData({
      closeBtn: false
    });
    return core.onShareAppMessage('/pages/goods/detail/index?id=' + this.data.goods.id, this.data.goods.title, thumb);
  },
  onShareTimeline: function (res) {
    let thumb = ''
    if (JSON.stringify(this.data.moreSel) != '{}') {
      thumb = this.data.moreSel.shareimg
    } else {
      thumb = this.data.goods.thumb
    }
    console.log(this.data.goods.title)
    return {
      title: this.data.goods.title,
      query: 'id=' + this.data.goods.id,
      imageUrl: thumb
    }
  },
  // 路由跳转
  navigateMf(e) {
    var url = e.currentTarget.dataset.url
    var re = /^[0-9]+.?[0-9]*/; //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/ 

    //跳转其他小程序
    if (url.appid) {
      wx.navigateToMiniProgram({
        appId: url.appid,
        path: url.urldata,
        extraData: {
          // foo: 'bar'
        }, //跳转到其他小程序传递的参数
        envVersion: 'develop',
        success(res) {
          wx.showModal({
            title: '跳转其他小程序',
            content: '',
            showCancel: false
          })
        },
        fail(res) {
          wx.showModal({
            title: '跳转失败',
            content: res.errMsg,
            showCancel: false
          })
        }
      })
    } else if (url.includes('?cate')) {
      let params = url.split('?')
      if (params[1].includes('cate')) {
        let cateid = params[1].split('=')[1]

        app.setCache("cateid", cateid)
      }
      wx.switchTab({
        url: url,
      })
    } else if (re.test(url)) {


      wx.makePhoneCall({
        phoneNumber: url //仅为示例，并非真实的电话号码
      })
    } else if (url == '/pages/index/index') {
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function () {
          wx.switchTab({
            url: url,
          })
        }
      })
    }
  },
  // banner事件
  //改变banner
  changeBanner(e) {
    this.setData({
      current: e.detail.current
    })
  },
  //开始播放
  startplay: function () {
    this.setData({
      cover: false
    });
    this.videoContext = wx.createVideoContext('myVideo');
    this.videoContext.play()
  },
  //切换为视频
  showvideo: function () {
    this.setData({
      showpic: false,
      showvideo: true
    });
    this.videoContext = wx.createVideoContext('myVideo');
    this.videoContext.play()
  },
  //切换为展示图片
  showpic: function () {
    this.setData({
      showpic: true,
      cover: false,
      showvideo: false
    });
    this.videoContext = wx.createVideoContext('myVideo');
    this.videoContext.pause()
  },
  //轮播图片的高
  imagesHeight: function (e) {
    var width = e.detail.width,
      height = e.detail.height,
      type = e.target.dataset.type,
      $this = this;
    var isdot = e.currentTarget.dataset.isdot
    wx.getSystemInfo({
      success: function (res) {
        if (isdot == "dot_inside") {
          $this.data.result[type] = Number(res.windowWidth / width * height);
        } else {
          $this.data.result[type] = Number(res.windowWidth / width * height) + 30;
        }
        if (!$this.data[type] || ($this.data[type] && result[type] < $this.data[type])) {
          $this.setData({
            result: $this.data.result
          });
        }
      }
    });
  },
  /**
   * 图片自适应
   */
  loadpic: function (event) {
    let pindex = event.currentTarget.dataset.idx
    let index = event.currentTarget.dataset.iid
    let specs = this.data.specs
    if (!specs) {
      return false
    }
    let picitems = specs[pindex].itemList
    let picWidth = event.detail.width
    let picHeight = event.detail.height
    picitems[index].styleCss = {
      width: picWidth,
      height: picHeight
    }
    this.setData({
      specs: specs
    })
  },

  //商品详情轮播图按照第一张图片显示
  imageLoad: function (e) {
    if (e.target.dataset.banner == 'banner') {
      let h = e.detail.height,
        w = e.detail.width,
        height = Math.floor((750 * h) / w);
      if (h == w) {
        this.setData({
          advHeight: 750
        })
      } else {
        this.setData({
          advHeight: height
        })
      }
    }
  },
  //送礼开关
  friendGiftStatus() {
    // cons
    let that = this
    let apicontent = api.markings.friendGiftStatus()
    core.post(apicontent, {}, function (res) {
      if (res.code == 1) {
        that.setData({
          showGiftStatus: res.data == "1"
        })
      }
    })
  },
  //点赞
  favorite: function (event) {
    var $this = this;
    var limits = $this.data.limits;
    if (limits) {
      var isfavorite = event.currentTarget.dataset.isfavorite ? 0 : 1;
      core.get('member/favorite/toggle', {
        'id': $this.data.options.id,
        'isfavorite': isfavorite
      }, function (ret) {
        if (ret.isfavorite) {
          $this.setData({
            'goods.isfavorite': 1
          });
        } else {
          $this.setData({
            'goods.isfavorite': 0
          });
        }
      })
    } else {
      // this.setData({ modelShow: true })
    }
  },

  /* 获取商品详情 */
  getDetail: function (options) {
    var $this = this;
    let apicontent = api.goods.goodsDetail()
    $this.setData({
      loading: true
    });
    core.get(apicontent, {
      id: options.id,
    }, function (result) {
      if (result.code != 1) {
        $this.setData({
          show: true,
          showgoods: false,
        });
        mainui.toast($this, result.message);
        setTimeout(function () {
          wx.navigateBack();
        }, 800);
      }

      if (result.data.goodsOptionList.length > 0) {
        // $this.setData({
        //   typeOption: result.data.goodsOptionList[0].type
        // })
      }

      let goods = result.data.goods
      let str = goods.thumbs
      let strs = new Array(); //定义一数组
      if (str) {
        if (str.includes(',')) {
          goods.thumbs = strs = str.split(","); //字符分割
        } else if (str == "") {
          goods.thumbs = []
        } else {
          goods.thumbs = [goods.thumbs]
        }
      }
      let goodsspecs = []
      result.data.goodsSpecList.forEach(e => {
        //判断该商品规格值是否显示，1为显示
        if (e.isMainSpec == 1) {
          goodsspecs.push(e)
        }
      })
      // 规格信息
      let specsData = []
      //规格值id

      let goodsSkuid = $this.data.options.goodsSkuid
      if (goodsSkuid) {
        //有规格值id
        let skuspecs = []
        result.data.goodsOptionList.forEach(e => {
          if (e.id == goodsSkuid) {
            let suk = e.specs.split(',')
            suk.forEach(ele => {
              skuspecs.push(ele.split(':')[1])
            })
          }

        })
        for (let index in goodsspecs) {
          goodsspecs[index].itemList.forEach(e => {
            if (e.title == skuspecs[index]) {
              specsData.push(e)
            }
          })
        }
      } else {
        goodsspecs.forEach(e => {
          let num = 0
          e.itemList.forEach(ele => {
            if (ele.status == 1) {
              num += 1
              specsData.push(ele)
            }
          })
          if (num == 0) {
            specsData.push(e.itemList[0])
          }
        })
      }
      // 没有规格值id
      let spectitle = [];
      // 初始化，默认规格
      for (let i in goodsspecs) {
        let spectitleitem = []
        spectitleitem[0] = goodsspecs[i].title
        spectitleitem[1] = specsData[i].title
        spectitle.push(spectitleitem)
      }
      $this.setData({
        show: true,
        goods: goods,
        specs: goodsspecs,
        spectitle,
        specsData,
        banner: goods.thumbs,
        goodsRecomsList: result.data.goodsRecomsList
      });
      wx.setNavigationBarTitle({
        title: goods.title || '商品详情'
      });
      if (result.data.goodsOptionList.length > 0) {
        $this.getgoodsSku()
      }
      app.sr.track('browse_sku_page', {

        "sku": {
          "sku_id": String(specsData[0].id),
          "sku_name": specsData[0].title
        },
        "spu": {
          "spu_id": String(goods.id),
          "spu_name": goods.title
        },
      })
    });
  },
  //获取购物车的总数
  getcartGoodsCount() {
    let apicontent = api.orders.cartGoodsCount()
    let memberId = app.getCache('userinfo_id');
    let $this = this
    core.post(apicontent, {
      memberId
    }, function (res) {
      if (res.data > 0) {
        $this.setData({
          cartcount: res.data,
        })
      }
    })
  },
  // 选规格
  specsTap: function (e) {
    this.setData({
      current: 0
    })
    // this.setData({
    //   isID: event.currentTarget.dataset.id
    // })
    var $this = this

    let index = e.currentTarget.dataset.idx
    let title = e.currentTarget.dataset.title
    let iid = e.currentTarget.dataset.iid
    // return false

    $this.data.spectitle[index][1] = title
    $this.data.specsData[index] = $this.data.specs[index].itemList[iid]

    $this.setData({
      spectitle: $this.data.spectitle,
      specsData: $this.data.specsData
    })
    $this.getgoodsSku()
    console.log(111)
  },
  //获取商品规格id
  getgoodsSku() {
    let $this = this
    let specs = []
    $this.data.spectitle.forEach(ele => {
      let eles = ele.join(":")
      specs.push(eles)
    })
    specs = specs.join(",")
    let apicontent = api.goods.getGoodsSku()
    core.post(apicontent, {
      id: $this.data.goods.id,
      specs,
    }, function (res) {
      if (res.code == 1) {

        let skubanner = res.data.banner ? JSON.parse(res.data.banner) : []

        let banner = $this.data.goods.thumbs

        let newBanner = []
        if (skubanner.length > 0) {
          skubanner.forEach(e => {
            newBanner.push(e)
          })
        }
        if (banner.length > 0) {
          banner.forEach(e => {
            newBanner.push(e)
          })
        }
        if (res.data.virtualStock <= 0) {
          $this.data.goods.status = 2
          $this.setData({
            banner: newBanner,
            moreSel: res.data,
            optionId: res.data.id,
            goods: $this.data.goods
          })
        } else {
          $this.data.goods.status = 1
          $this.setData({
            banner: newBanner,
            moreSel: res.data,
            optionId: res.data.id,
            goods: $this.data.goods
          })
        }
      }
    })
  },
  bindgetuserinfo() {
    var that = this;
    authScope.scopeLogin().then((res) => {
      if (res) {
        that.setData({
          isLogin: true
        })
      }
    })
  },
  //价格数量加减
  numberSelect(e) {
    let $this = this
    console.log(e)
    let total = this.data.total
    let action = e.currentTarget.dataset.action
    if (action == "minus") {
      if (total == 1) {
        wx.showToast({
          title: '最少购买一件',
          icon: "none"
        })
        return false
      }
      total--
      $this.setData({
        total
      })
    } else {
      total++
      $this.setData({
        total
      })
    }
  }
}))